<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\wxapp\controller;

use api\wxapp\controller\ApiBaseController;
use think\Db;
use api\wxapp\model\Diary;
use api\wxapp\model\Score;
use api\wxapp\model\Config;
use api\wxapp\model\User;
class DiaryController extends ApiBaseController
{

    public function index(Diary $diary)
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $page = isset($params['page']) ? $params['page'] : 1;
        $list = $diary->getList($page,$params['uid']);
        $this->success('请求成功!',$list);
    }
    public function add()
    {
        $params = $this->getParam();
        $this->checkuid($params);
        $this->checkimg($params);
        $this->checkcontent($params);
        Db::startTrans();
        try{
            $params['addtime'] = $this->returnDateTime();
            $res = Diary::insert($params);
            if(!$res){
                throw new \Exception('日记发表失败');
            }
            //查询发表日记赠送多少积分
            //查询当日是否 已经赠送过积分
            $find = Score::where(['uid'=>$params['uid'],'type'=>3,'time'=>date('Y-m-d',time())])->find();
            if(!$find){
                $score = Config::where('id',12)->value('value');
                $data['uid'] = $params['uid'];
                $data['integral'] = $score;
                $data['type'] = 3;
                $data['status'] = 1;
                $data['time'] = date('Y-m-d',time());
                $data['addtime'] = date('Y-m-d H:i:s',time());
                $data['remark'] = '发表日记获得积分';
                $res1 = Score::insert($data);
                if(!$res1){
                    throw new \Exception('积分记录储存失败!!!');
                }
                //更新用户积分
                $res2 = User::where('id',$params['uid'])->setInc('integral',$score);
                if(!$res2){
                    throw new \Exception('用户积分更新失败');
                }
            }
            Db::commit(); //提交事务
        }catch(\Exception $e){
            Db::rollback(); //回滚事务
            $this->error($e->getMessage());
        }
        $this->success('发表成功!',true);
    }
    public function delete()
    {
        $params = $this->getParam();
        $this->checkid($params);
        $res = Diary::destroy($params['id']);
        if($res){
            $this->success('请求成功!');
        }else{
            $this->error('请求失败!!!!');
        }
    }
}
